package controller;


import beans.Car;
import utils.JDBCUtils;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class RemoveFromCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String goodsId = request.getParameter("goods_id");
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("user_id");

        // 检查是否登录，如果没有登录，userId 可能是 null
        if (userId == null) {
            // 如果没有登录，重定向到登录页面
            response.sendRedirect("login.jsp");
            return;
        }

        Connection connection = null;
        PreparedStatement stmt = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "DELETE FROM car WHERE goods_id=? AND userid=?";
            stmt = connection.prepareStatement(sql);
            stmt.setString(1, goodsId);
            stmt.setString(2, userId);
            int rowsAffected = stmt.executeUpdate();

            if (rowsAffected > 0) {
                // 从session中移除已删除的商品
                @SuppressWarnings("unchecked")
                List<Car> carList = (List<Car>) session.getAttribute("carList");
                if (carList != null) {
                    carList.removeIf(car -> car.getGoods_id().equals(goodsId));
                }
                // 重定向到购物车页面
                response.sendRedirect("car.jsp");
            } else {
                // 如果没有找到对应的记录，可能是数据库中没有该商品或用户未登录
                response.sendRedirect("error.jsp"); // 假设有一个错误页面error.jsp
            }
        } catch (SQLException e) {
            throw new ServletException("Database access error", e);
        } finally {
            JDBCUtils.close(stmt, connection);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}